package com.yidi.system.service.imp;

import com.yidi.common.annotation.DataScope;
import com.yidi.common.constant.UserConstants;
import com.yidi.common.core.domain.AjaxResult;
import com.yidi.common.core.domain.TreeSelect;
import com.yidi.common.core.domain.entity.SysDept;
import com.yidi.common.core.domain.entity.SysRole;
import com.yidi.common.core.domain.entity.SysUser;
import com.yidi.common.core.service.imp.AbstractBaseService;
import com.yidi.common.enums.RemoveEnum;
import com.yidi.common.exception.ServiceException;
import com.yidi.common.utils.SecurityUtils;
import com.yidi.common.utils.StringUtils;
import com.yidi.common.utils.spring.SpringUtils;
import com.yidi.system.repository.SysDeptRepository;
import com.yidi.system.service.SysDeptService;
import com.yidi.system.service.SysRoleService;
import com.yidi.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.Predicate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ：Xn
 * @ClassName: SysDeptServiceImpl
 * @date ：2021-10-19 14:35
 * @describe ：
 */
@Service
public class SysDeptServiceImpl extends AbstractBaseService<SysDept> implements SysDeptService {

    @Autowired
    private SysDeptRepository sysDeptRepository;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @PersistenceContext
    private EntityManager em;

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectDeptList(SysDept dept)
    {
        StringBuilder sql = new StringBuilder(
                "select d.id, d.parent_id, d.ancestors, d.dept_name, d.order_num, d.leader, d.phone, d.email, d.status, d.remove_status, d.create_by, d.create_time from sys_dept d" +
                        " where d.remove_status = 0");

        if(dept.getId() != null){
            sql.append(" and d.id = ").append(dept.getId());
        }

        if(dept.getParentId() != null){
            sql.append(" and d.parent_id = ").append(dept.getParentId());
        }

        if(StringUtils.isNotBlank(dept.getDeptName())){
            sql.append(" and d.dept_name like concat('%','").append(dept.getDeptName()).append("', '%')");
        }

        if(StringUtils.isNotBlank(dept.getStatus())){
            sql.append(" and d.status = '").append(dept.getStatus()).append("'");
        }

        if(dept.getParams() != null){
            Map<String, Object> params = dept.getParams();
            String sqlString = (String)params.get("dataScope");
            if(StringUtils.isNotBlank(sqlString)){
                sql.append(sqlString);
            }
        }

        sql.append(" order by d.parent_id, d.order_num");

        Query query = em.createNativeQuery(sql.toString());
        List<Object[]> list = query.getResultList();
        List<SysDept> deptList = new ArrayList<SysDept>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for(Object[] objects : list){
            SysDept d = new SysDept();
            d.setId(Long.parseLong(objects[0].toString()));
            d.setParentId(Long.parseLong(objects[1].toString()));
            d.setAncestors(objects[2].toString());
            d.setDeptName(objects[3].toString());
            d.setOrderNum(Integer.parseInt(objects[4].toString()));
            d.setLeader(objects[5].toString());
            d.setPhone(objects[6].toString());
            d.setEmail(objects[7].toString());
            d.setStatus(objects[8].toString());
            d.setRemoveStatus(Integer.parseInt(objects[9].toString()));
            d.setCreateBy(objects[10].toString());
            try {
                d.setCreateTime(format.parse(objects[11].toString()));
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            deptList.add(d);
        }

        return deptList;
    }

    /**
     * 校验部门是否有数据权限
     *
     * @param deptId 部门id
     */
    @Override
    public void checkDeptDataScope(Long deptId)
    {
        SysUser u = sysUserService.findById(SecurityUtils.getUserId());
        if (!SysUser.isAdmin(u.getUserName()))
        {
            SysDept dept = new SysDept();
            dept.setId(deptId);
            List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
            if (StringUtils.isEmpty(depts))
            {
                throw new ServiceException("没有权限访问部门数据！");
            }
        }
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts)
    {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts)
    {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysDept dept : depts)
        {
            tempList.add(dept.getId());
        }
        for (Iterator<SysDept> iterator = depts.iterator(); iterator.hasNext();)
        {
            SysDept dept = (SysDept) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId()))
            {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Integer> selectDeptListByRoleId(Long roleId)
    {
        SysRole role = sysRoleService.findById(roleId);
        return sysDeptRepository.selectDeptListByRoleId(roleId);
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public String checkDeptNameUnique(SysDept dept)
    {
        Long deptId = StringUtils.isNull(dept.getId()) ? -1L : dept.getId();
        SysDept info = sysDeptRepository.findByDeptNameAndParentId(dept.getDeptName(), dept.getParentId());
        if (StringUtils.isNotNull(info) && !info.getId().equals(deptId))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public AjaxResult insertDept(SysDept dept)
    {
        SysDept sup = findById(dept.getParentId());
        // 如果父节点不为"正常"状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(sup.getStatus()))
        {
            return AjaxResult.error("上级部门已停用，不允许新增");
        }
        dept.setAncestors(sup.getAncestors() + "," + dept.getParentId());

        add(dept);

        return AjaxResult.success();
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public Integer selectNormalChildrenDeptById(Long deptId)
    {
        return sysDeptRepository.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     */
    @Override
    public void updateDept(SysDept dept)
    {
        //新父类
        SysDept newParentDept = findById(dept.getParentId());
        SysDept oldDept = findById(dept.getId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
        {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getId();
            String oldAncestors = oldDept.getAncestors();

            oldDept.setParentId(dept.getParentId());
            oldDept.setAncestors(newAncestors);
            updateDeptChildren(oldDept.getId(), newAncestors, oldAncestors);
        }
        oldDept.setDeptName(dept.getDeptName());
        oldDept.setOrderNum(dept.getOrderNum());
        oldDept.setLeader(dept.getLeader());
        oldDept.setPhone(dept.getPhone());
        oldDept.setEmail(dept.getEmail());
        oldDept.setStatus(dept.getStatus());
        modify(oldDept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatus(dept);
        }
    }

    /**
     * 是否存在子节点
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(Long deptId)
    {
        int result = sysDeptRepository.hasChildByDeptId(deptId);
        return result > 0 ? true : false;
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId)
    {
        int result = sysDeptRepository.checkDeptExistUser(deptId);
        return result > 0 ? true : false;
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public void deleteDeptById(Long deptId)
    {
        remove(deptId);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t)
    {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t)
    {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext())
        {
            SysDept n = (SysDept) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().equals(t.getId()))
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }

    /**
     * 修改子元素关系
     *
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors)
    {
        List<SysDept> children = sysDeptRepository.selectChildrenDeptById(deptId);
        for (SysDept child : children)
        {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
            modify(child);
        }
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatus(SysDept dept)
    {

        if(dept.getParentId() == 0L) {

        }else {
            SysDept sup = findById(dept.getParentId());
            sup.setStatus(UserConstants.DEPT_NORMAL);
            modify(sup);
            updateParentDeptStatus(sup);
        }

    }
}
